<template>
  <div class="bg courseRecord-container">

    <!-- 查询区域 -->
    <div>
      <el-input style="width: 200px" clearable prefix-icon="el-icon-c-scale-to-original"
                @keyup.enter.native="load(1)"  placeholder="查询预约内容" v-model="content"></el-input>
      <el-input style="width: 200px; margin: 0 5px" prefix-icon="el-icon-search"
                @keyup.enter.native="load(1)" placeholder="查询发起时间" v-model="createTime"></el-input>
      <el-button type="primary" style="margin: 0 5px" @click="load(1)">查询</el-button>
      <el-button type="info" style="margin: 0 5px" @click="reset">重置</el-button>
      <el-select v-model="state" style="margin: 0 5px" placeholder="筛选预约状态">
        <el-option label="待审核" value="待审核"></el-option>
        <el-option label="已通过" value="已通过"></el-option>
        <el-option label="已完成" value="已完成"></el-option>
        <el-option label="已拒绝" value="已拒绝"></el-option>
        <el-option label="已取消" value="已取消"></el-option>
      </el-select>
    </div>

    <!-- 增删区域 -->
    <div style="margin: 10px 0">
      <el-button type="info" plain @click="exportData">批量导出</el-button>
    </div>

    <!-- 数据表格区域 -->
    <el-table :data="tableData" stripe class="datatable"
              :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="content" label="预约内容" sortable></el-table-column>
      <el-table-column prop="description" label="详情" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createTime" label="发起时间" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.createTime">{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="reserveTime" label="预约时间" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.reserveTime">{{ formatDate(scope.row.reserveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="state" label="状态" sortable></el-table-column>
      <el-table-column prop="handler" label="处理人" sortable></el-table-column>
      <el-table-column prop="handlerTime" label="处理时间" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.handlerTime">{{ formatDate(scope.row.handlerTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain
                     v-if="scope.row.state === '待审核'"
                     @click="handleEdit(scope.row)">添加备注</el-button>
          <el-button size="mini" type="danger" plain
                     v-if="scope.row.state === '待审核'"
                     @click="cancel(scope.row.id)">取消</el-button>
          <el-button size="mini" type="success" plain
                     v-if="scope.row.state === '已通过'"
                     @click="finish(scope.row.id); ">完成</el-button>
          <el-button size="mini" type="primary" plain
                     v-if="scope.row.state === '已完成'"
                     @click="doComment(scope.row)">评价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器区域 -->
    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <!-- 步骤条 -->
    <div style="position: fixed; bottom: 20px; width: 85%; padding: 10px">
      <el-steps :active=2 align-center>
        <el-step title="学员预约课程" icon="el-icon-c-scale-to-original"
                 description="请仔细确认预约的内容是否正确，预约一旦通过无法取消，特殊情况请联系管理员或教练"></el-step>
        <el-step title="等待审核" icon="el-icon-c-scale-to-original"
                 description="1、预约内容审核后主页有消息提醒请及时查看；2、如果需要指定教练，请添加备注（优先安排空闲教练）"></el-step>
        <el-step title="完成预约" icon="el-icon-circle-check"
                 description="在完成相关活动后即视为该预约已完成，可以由任意一方确定完成"></el-step>
        <el-step title=学员评价 icon="el-icon-circle-check"
                 description="（可选）学员可为相关课程、车辆和教练进行评价，发布其他无关内容造成的损失本平台概不负责"></el-step>
      </el-steps>
    </div>

    <!-- 添加备注对话框 -->
    <el-dialog title="备注信息" :visible.sync="remarkVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" @keyup.enter.native="save()"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="remarkVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog title="评价信息" :visible.sync="commentVisible" width="40%">
      <el-form :model="commentForm" label-width="80px" style="padding-right: 20px" :rules="commentRule"
               ref="commentFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="评价项目：" label-width="100px">
              {{commentForm.content}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评价教练：" label-width="100px">
              {{commentForm.handler}}
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: right;">
          </el-col>
        </el-row>
        <el-form-item label="评价" prop="content">
          <el-input type="textarea" v-model="commentForm.userContent"
                    @keyup.enter.native="saveComment()" placeholder="请输入评价，禁止输入无关内容">
          </el-input>
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-select v-model="commentForm.score" placeholder="请选择教练和项目总评分">
            <el-option label="10分" value="10分"></el-option>
            <el-option label="9分" value="9分"></el-option>
            <el-option label="8分" value="8分"></el-option>
            <el-option label="7分" value="7分"></el-option>
            <el-option label="6分" value="6分"></el-option>
            <el-option label="5分" value="5分"></el-option>
            <el-option label="4分" value="4分"></el-option>
            <el-option label="3分" value="3分"></el-option>
            <el-option label="2分" value="2分"></el-option>
            <el-option label="1分" value="1分"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commentVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveComment">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
export default {
  name: "Course_record",

  // 组件的数据对象
  data() {
    return {
      tableData: [],  // 存储所有的课程预约记录数据
      pageNum: 1,   // 当前页码
      pageSize: 5,  // 每页显示的数据条数
      form: {},    // 存储表单数据，用于添加或编辑备注
      commentForm: {}, // 存储评价表单数据
      createTime: '', // 查询的预约发起时间
      content: '', // 查询的预约内容
      state: '', // 查询的预约状态
      remarkVisible: false, // 控制备注弹窗的显示与隐藏
      commentVisible: false, // 控制评价弹窗的显示与隐藏
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'), // 从本地存储获取用户信息
      rules: {  // 表单验证规则
        remark: [{required: true, message: '请输入备注', trigger: 'blur'}]
      },
      commentRule: {  // 评价表单验证规则
        score: [{required: true, message: '请选择评分', trigger: 'blur'}]
      },
      ids: [] // 存储选中的课程预约记录 ID 数组
    }
  },

  // 组件创建时调用 load 方法加载数据
  created() {
    this.load(1)
  },

  methods: {
    // 格式化日期的方法
    formatDate(date) {
      const options = {year: 'numeric', month: 'long', day: 'numeric'};
      return new Date(date).toLocaleDateString('zh-CN', options);
    },
    // 处理表格行选中变化
    handleSelectionChange(rows) {   // 获取选中的行数据
      this.ids = rows.map(v => v.id)
    },

    // 重置查询条件的方法
    reset() {
      this.content = ''
      this.createTime = ''
      this.state = ''
      this.load()
    },
    // 完成预约的方法
    finish(id) {
      this.$confirm('您确认完成了这个预约吗？', '完成预约', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning"
      }).then(() => {
        // 发送更新预约状态为已完成的请求
        this.$request.put(`/reserve/handle/${id}`, {state: '已完成'}).then(res => {
          if (res.code === '200') {
            this.$message.success('课程/车辆已成功完成');
            this.load(1);
          } else {
            this.$message.error(res.msg);
          }
        }).catch(() => {})
      }).catch(() => {})
    },

    // 进行评价的方法
    doComment(row) {
      this.commentForm = JSON.parse(JSON.stringify(row));  // 深拷贝数据
      this.commentVisible = true;
    },

    // 取消预约的方法
    cancel(id) {
      this.$confirm('您确认要取消这个预约吗？', '取消预约', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning"
      }).then(() => {
        // 发送更新预约状态为已取消的请求
        this.$request.put(`/reserve/handle/${id}`, {state: '已取消'}).then(res => {
          if (res.code === '200') {
            this.$message.success('预约已成功取消');
            this.load(1);
          } else {
            this.$message.error(res.msg);
          }
        }).catch(() => {})
      }).catch(() => {})
    },

    // 批量导出 excel 的方法
    exportData() {
      if (!this.ids.length) { // 没有选择行时全部导出
        window.open('http://localhost:9090/reserve/export?content=' + this.content)
      } else {
        let idStr = this.ids.join(',')
        window.open('http://localhost:9090/reserve/export?ids=' + idStr);
      }
    },

    // 编辑数据的方法
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row));  // 深拷贝数据
      this.remarkVisible = true;   // 打开备注弹窗
    },

    // 保存数据的方法
    save() {   // 保存按钮触发的逻辑
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/reserve/update' : '/reserve/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 保存成功
              this.$message.success('保存成功')
              this.load(1)
              this.remarkVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误信息
            }
          })
        }
      })
    },

    // 保存评价的方法
    saveComment() {
      this.$request.post('/comment/create', {
        title: this.commentForm.content,
        coach: this.commentForm.handler,
        score: this.commentForm.score,
        content: this.commentForm.userContent,
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('评价成功');
          this.commentVisible = false;
        } else {
          this.$message.error('评价失败: ' + res.msg);
        }
      }).catch(error => {
        this.$message.error('评价发生错误: ' + error);
      });
    },

    // 加载数据的方法
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/reserve/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          content: this.content,
          createTime: this.createTime,
          username: this.user.username,
          state: this.state,
          reserveTime: '',
          type: '课程',
          remark: '',
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },

    // 处理分页变化的方法
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },

  }
}
</script>


<style scoped>
.courseRecord-container{
  background:
      linear-gradient(rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.3)), /* 白色半透明遮罩让颜色变淡 */
      url('~@/assets/bg/courseRecord.png') center/cover no-repeat;
}
</style>